package threadTest;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.bouncycastle.asn1.sec.SECNamedCurves;
import org.jfree.data.time.Second;


public class CallableAndFuture {
	
	static class Worker{
		public int age;
		public int getAge() {
			return age;
		}
		public void setAge(int age) {
			this.age = age;
		}
	}

	static class MyCall<Worker> implements Callable<Worker>{
		public Worker w;
		public MyCall(Worker w){
			this.w = w;
		}
		public Worker call() throws Exception {
			while(!stop){
				TimeUnit.SECONDS.sleep(1);
				System.out.println("call working.");
			}
			Worker w2 = w;
			System.out.println("quit.");
			return w2;
		}
	}
	static boolean stop;
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		ExecutorService es = Executors.newCachedThreadPool();
		Worker w = new Worker();
		w.setAge(10);
		MyCall<Worker> myCall = new MyCall<Worker>(w);
		Future<Worker> task = es.submit(myCall);
		es.shutdown();
		System.out.println("shutdown");
		try {
			TimeUnit.SECONDS.sleep(2);
			System.out.println("sleeped,wake up.");
//			stop=true;
			System.out.println(task.get(2,TimeUnit.SECONDS));
			System.out.println("1="+task.isDone());
			System.out.println("2="+task.isCancelled());
			task.cancel(true);
			System.out.println("3="+task.isDone());
			System.out.println("4="+task.isCancelled());
			System.out.println("end");
		} catch (InterruptedException e) {
		} catch (ExecutionException e) {
		} catch (TimeoutException e) {
			System.out.println("time out!");
			System.out.println("5="+task.isDone());
			System.out.println("6="+task.isCancelled());
			task.cancel(true);
			System.out.println("7="+task.isDone());
			System.out.println("8="+task.isCancelled());
			System.out.println("catch end.");
		}
	}
}
